Page({
  /**
   * 页面的初始数据
   */
  data: {
    ischeck: '1',
    checked: false,
    dataSet: [],
    petItems: [],
    remindList: [],
    minDate: '',
    maxDate: '',
    show: false,
    preSelectedType: null,
    currentDate: '' // 新增：用于记录当前显示的日期
  },

  // 常量定义 - 提取重复的初始数据
  constants: {
    INIT_PET_ITEMS: [
      { "id": 1, "title": "饮食", "icon": "/images/jilu/food.png", "arrow": true, "action": { "text": "", "info": "" } },
      { "id": 2, "title": "喝水", "icon": "/images/jilu/water.png", "action": { "text": "", "icon": true } },
      { "id": 3, "title": "体重", "icon": "/images/jilu/heavy.png", "action": { "text": "", "icon": true } },
      { "id": 4, "title": "洗护", "icon": "/images/jilu/wash.png", "arrow": true, "action": { "text": "", "info": "" } },
      { "id": 5, "title": "尿便", "icon": "/images/jilu/shi.png", "arrow": true, "action": { "tags": "" } },
      { "id": 6, "title": "记事", "icon": "/images/jilu/jishi.png", "action": { "camera": true, "text": "" } },
      { "id": 7, "title": "异常", "icon": "/images/jilu/warn.png", "arrow": true, "action": { "text": "" } },
      { "id": 8, "title": "用药", "icon": "/images/jilu/yao.png", "arrow": true, "action": { "text": "" } }
    ],
    INIT_REMIND_LIST: []
  },

  // 标题选择
  handelCheck(ev) {
    let { id } = ev.currentTarget.dataset
    this.setData({ ischeck: id })
  },

  // 日历数据处理
  formatDate(date) {
    const targetDate = new Date(date);
    const year = targetDate.getFullYear();
    const month = (targetDate.getMonth() + 1).toString().padStart(2, '0');
    const day = targetDate.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 日历选择事件
  handelConfirm(event) {
    let checkdate = this.formatDate(event.detail)
    this.updateData(checkdate)
  },

  // 提醒修改
  async onChange(ev) {
    const { id } = ev.currentTarget.dataset;
    const { remindList } = this.data;
    
    const index = remindList.findIndex(item => item.id == id);
    if (index !== -1) {
      // 创建新数组副本
      const newRemindList = [...remindList];
      newRemindList[index] = { ...newRemindList[index], checked: ev.detail };
      
      // 更新页面数据
      this.setData({ remindList: newRemindList });
      
      // 获取当前存储的数据集并更新
      let dataset = this.getLocalDataset();
      dataset.remindListId = newRemindList;
      
      // 统一保存到本地和服务器
      await this.saveDataset(dataset);
    }
  },

  // 添加提醒
  handelAdd() {
    wx.navigateTo({ url: `/pages/detail/index` });
  },

  // 弹窗遮罩
  handelOpen(ev) {
    let { type } = ev.currentTarget.dataset
    this.setData({ show: true, preSelectedType: type })
  },

  // 关闭遮罩
  handelClose() {
    this.setData({ show: false })
  },

  // 接收子组件返回的更新后的数据
  async handleUpdate(e) {
    const updatedItem = e.detail;
    const { title } = updatedItem;
    
    // 更新 petItems 中的对应项
    const newPetItems = this.data.petItems.map(item => 
      item.title === title ? { ...item, ...updatedItem } : item
    );
    
    // 更新页面数据
    this.setData({ petItems: newPetItems });
    wx.showToast({ title: '数据更新成功' });
    
    // 获取当前数据集并更新
    let dataset = this.getLocalDataset();
    dataset.petItems = newPetItems;
    
    // 统一保存到本地和服务器
    await this.saveDataset(dataset);
  },

  // 获取事件列表
  async updateData(date) {
    try {
      const openid = '111'; // 实际应从全局获取
      const res = await getApp().flyio.get('/data_set', { openid });
      let todayData = res.data.find(item => item.date === date);
      
      // 若当天无数据，初始化新数据
      if (!todayData) {
        const initData = {
          openid,
          date,
          petItems: this.constants.INIT_PET_ITEMS,
          remindListId: this.constants.INIT_REMIND_LIST
        };
        const initRes = await getApp().flyio.post('/data_set', initData);
        todayData = initRes.data;
      }
      
      // 更新页面数据并保存到本地
      this.setData({
        petItems: todayData.petItems,
        remindList: todayData.remindListId,
        currentDate: date // 保存当前日期
      });
      this.setLocalDataset(todayData);
      
    } catch (error) {
      console.error("数据处理失败：", error);
      // 失败时使用初始数据
      this.setData({
        petItems: this.constants.INIT_PET_ITEMS,
        remindList: this.constants.INIT_REMIND_LIST
      });
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    }
  },

  /**
   * 本地存储操作封装
   */
  // 获取本地数据集
  getLocalDataset() {
    return wx.getStorageSync('dataset') || {};
  },

  // 设置本地数据集
  setLocalDataset(data) {
    wx.setStorageSync('dataset', data);
    return data;
  },

  /**
   * 统一保存数据到本地和服务器
   * @param {Object} dataset - 要保存的数据集
   */
  async saveDataset(dataset) {
    try {
      // 先更新本地存储
      this.setLocalDataset(dataset);
      
      // 再更新服务器
      if (dataset.id) {
        const res = await getApp().flyio.put(`/data_set/${dataset.id}`, dataset);
        console.log("数据库更新结果", res);
        return res.data;
      }
    } catch (e) {
      console.error("数据保存失败:", e);
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const nowdate = this.formatDate(new Date());
    this.updateData(nowdate);
  },

  /**
   * 生命周期函数--监听页面显示
   * 从其他页面返回时会触发此函数，在这里更新数据
   */
  onShow() {
    // 如果已有当前日期，则更新该日期的数据
    if (this.data.currentDate) {
      this.updateData(this.data.currentDate);
    } else {
      // 如果没有当前日期，则使用今天的日期
      const nowdate = this.formatDate(new Date());
      this.updateData(nowdate);
    }
  },

  /**
   * 其他生命周期函数保持不变
   */
  onReady() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})
